package com.eling.elcms.travel.service.impl;

import com.eling.elcms.basedoc.model.PersonalInfo;
import com.eling.elcms.basedoc.service.IPersonalInfoManager;
import com.eling.elcms.core.AppContext;
import com.eling.elcms.core.service.impl.GenericManagerImpl;
import com.eling.elcms.core.util.PropertyUtils;
import com.eling.elcms.core.webapp.controller.Msg;
import com.eling.elcms.questionnaire.model.QuestionAnswer;
import com.eling.elcms.questionnaire.model.QuestionAnswerSheet;
import com.eling.elcms.questionnaire.service.IQuestionAnswerSheetService;
import com.eling.elcms.system.model.CommonUser;
import com.eling.elcms.travel.dao.ICustomerVisitRecordDao;
import com.eling.elcms.travel.model.Customer;
import com.eling.elcms.travel.model.Customer.DataSource;
import com.eling.elcms.travel.model.CustomerVisitRecord;
import com.eling.elcms.travel.model.CustomerVisitRecord.RecordType;
import com.eling.elcms.travel.model.TravelContract;
import com.eling.elcms.travel.model.TravelContract.Status;
import com.eling.elcms.travel.model.TravelContract.VisitStatus;
import com.eling.elcms.travel.model.Visit;
import com.eling.elcms.travel.service.ICustomerManager;
import com.eling.elcms.travel.service.ICustomerVisitRecordManager;
import com.eling.elcms.travel.service.IRoomPersonalInfoManager;
import com.eling.elcms.travel.service.ITravelContractManager;
import com.eling.elcms.travel.service.IVisitManager;
import com.eling.elcms.visit.model.view.QuestionAnswerSheetView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CustomerVisitRecordManagerImpl extends GenericManagerImpl<CustomerVisitRecord, Long>
		implements ICustomerVisitRecordManager {

	ICustomerVisitRecordDao customerVisitRecordDao;

	@Autowired
	private ICustomerManager customerManager;

	@Autowired
	private IPersonalInfoManager personalInfoManager;

	@Autowired
	private IQuestionAnswerSheetService questionAnswerSheetService;
	@Autowired
	IVisitManager visitManager;
	@Autowired
	private ITravelContractManager travelContractManager;
	@Autowired
	private IRoomPersonalInfoManager roomPersonalInfoManager;

	@Autowired
	public void setDao(ICustomerVisitRecordDao dao) {
		this.dao = dao;
		this.customerVisitRecordDao = dao;
	}

	@Override
	public Msg saveAll(String type, Integer customerVersion, Customer customer, CustomerVisitRecord cvr,
			QuestionAnswerSheet questionAnswerSheet, QuestionAnswerSheetView questionAnswerSheetView) {

		customer = saveCustomer(type, customerVersion, customer, cvr);

		if (questionAnswerSheet.getPkQuestionAnswerSheet() == null) {
			questionAnswerSheet = questionAnswerSheetService.save(questionAnswerSheet);
		}
		if(questionAnswerSheetView.getList() != null && !questionAnswerSheetView.getList().isEmpty()){
			for (QuestionAnswer questionAnswer : questionAnswerSheetView.getList()) {
				questionAnswer.setQuestionAnswerSheet(questionAnswerSheet);
			}
			
			questionAnswerSheet.setQuestionAnswers(new HashSet<>(questionAnswerSheetView.getList()));
			cvr.setQuestionAnswerSheet(questionAnswerSheet);
		}

		customer.setDataSource(DataSource.Visit);
		customer.setSaleConsultant(cvr.getSaleConsultant());
		customer.setProductType(cvr.getProductType());
		PersonalInfo personalInfo = customer.getPersonalInfo();
		if(personalInfo.getIdNumber()!=null){
			if(personalInfo.getIdNumber() == ""){
				personalInfo.setIdNumber(null);
			}else{
				PersonalInfo pInfo = roomPersonalInfoManager.queryById(personalInfo.getIdNumber());
				if(pInfo == null){
					personalInfo = personalInfoManager.save(personalInfo);
				}else {
					if(personalInfo.getName()!=null){
						pInfo.setName(personalInfo.getName());
					}
					if(personalInfo.getSex()!=null){
						pInfo.setSex(personalInfo.getSex());
					}	
					if(personalInfo.getMobilePhone()!=null){
						pInfo.setMobilePhone(personalInfo.getMobilePhone());
					}	
					if(personalInfo.getBirthday()!=null){
						pInfo.setBirthday(personalInfo.getBirthday());
					}	
					if(personalInfo.getElectronicMail()!=null){
						pInfo.setElectronicMail(personalInfo.getElectronicMail());
					}	
					if(personalInfo.getHouseRegister()!=null){
						pInfo.setHouseRegister(personalInfo.getHouseRegister());
					}	
					if(personalInfo.getAddress()!=null){
						pInfo.setAddress(personalInfo.getAddress());
					}	
					personalInfo = personalInfoManager.save(pInfo);
				}
			}
			customer.setPersonalInfo(personalInfo);
		}
		cvr.setCustomer(customerManager.save(customer));

		try {
			save(cvr);
			log.debug("保存成功！");
		} catch (Exception e) {
			log.debug("保存失败！");
			throw e;
		}

		return new Msg("保存成功");
	}

	@Override
	public Msg saveContract(Long pkTravelContract, CustomerVisitRecord cvr, QuestionAnswerSheet questionAnswerSheet,
			QuestionAnswerSheetView questionAnswerSheetView) {
		if (questionAnswerSheet.getPkQuestionAnswerSheet() == null) {
			questionAnswerSheet = questionAnswerSheetService.save(questionAnswerSheet);
		}
		List<QuestionAnswer> list = questionAnswerSheetView.getList();
		for (QuestionAnswer questionAnswer : list) {
			questionAnswer.setQuestionAnswerSheet(questionAnswerSheet);
		}
		questionAnswerSheet.setQuestionAnswers(new HashSet<QuestionAnswer>(list));
		cvr.setQuestionAnswerSheet(questionAnswerSheet);
		CustomerVisitRecord record = new CustomerVisitRecord();
		PropertyUtils.setProperty(record, "visit.id", pkTravelContract);
		List<CustomerVisitRecord> recordlist = customerVisitRecordDao.query(record);
		Visit visit = new Visit();
		if (recordlist.isEmpty()) {
			visit.setId(pkTravelContract);
			visit.setType(com.eling.elcms.travel.model.Visit.Type.Contract);
			visit.setVersion(0);
			// 保存visit
			visit = visitManager.save(visit);
		} else {
			visit = recordlist.get(0).getVisit();
		}
		cvr.setVisit(visit);
		cvr.setVisitDate(new Date());
		cvr.setSaleConsultant((CommonUser) AppContext.curUser());
		try {
			save(cvr);
			TravelContract travel = travelContractManager.get(pkTravelContract);
			travel.setVisitStatus(TravelContract.VisitStatus.Visit);
			travelContractManager.save(travel);
			log.debug("保存成功！");
		} catch (Exception e) {
			log.debug("保存失败！");
			throw e;
		}

		return new Msg("保存成功");
	}

	public Customer saveCustomer(String type, Integer customerVersion, Customer customer, CustomerVisitRecord cvr) {
		customer.setVersion(customerVersion);
		customer.setTransMember(false);
		if (null != customer.getPkCustomer()) {
			Customer cus1 = customerManager.get(customer.getPkCustomer());
			if (type.equals("Visit")) { // 来访
				customer.setVisitTime(cvr.getVisitDate());
				customer.setVisitCount(cus1.getVisitCount() + 1);
				customer.setReturnVisitCount(cus1.getReturnVisitCount());
				customer.setReturnVisitTime(cus1.getReturnVisitTime());
			}
			if (type.equals("Return")) { // 回访
				customer.setReturnVisitTime(cvr.getVisitDate());
				customer.setReturnVisitCount(cus1.getReturnVisitCount() + 1);
				customer.setVisitCount(cus1.getVisitCount());
				customer.setVisitTime(cus1.getVisitTime());
			}
			if ("".equals(type)) { // 编辑
				customer.setVisitCount(cus1.getVisitCount());
				customer.setReturnVisitCount(cus1.getReturnVisitCount());
				if (cvr.getRecordType().equals(RecordType.Visit)) {
					customer.setVisitTime(cvr.getVisitDate());
					customer.setReturnVisitTime(cus1.getReturnVisitTime());
				} else {
					customer.setVisitTime(cus1.getVisitTime());
					customer.setReturnVisitTime(cvr.getVisitDate());
				}
			}
		} else {
			if (type.equals("Visit")) {
				customer.setVisitTime(cvr.getVisitDate());
				customer.setVisitCount(1);
				customer.setReturnVisitCount(0);
			} else {
				customer.setReturnVisitTime(cvr.getVisitDate());
				customer.setReturnVisitCount(1);
				customer.setVisitCount(0);
			}
		}
		return customer;
	}

	@Override
	public List<CustomerVisitRecord> queryAll(CustomerVisitRecord cond) {
		List<CustomerVisitRecord> cvrList = query(cond);
		List<CustomerVisitRecord> returnList = new ArrayList<CustomerVisitRecord>();
		if (!cvrList.isEmpty()) {
			List<Long> pkCustomerList = cvrList.stream().map(a -> a.getCustomer().getPkCustomer())
					.collect(Collectors.toList());
			Customer cus = new Customer();
			PropertyUtils.setProperty(cus, "pkCustomerIn", pkCustomerList);
			List<Customer> customerList = customerManager.query(cus);
			for (Customer c : customerList) {
				for (CustomerVisitRecord cvr : cvrList) {
					if (cvr.getCustomer().getPkCustomer().equals(c.getPkCustomer())) {
						if (cond.getRecordType().equals(RecordType.Visit)
								&& cvr.getVisitDate().getTime() == c.getVisitTime().getTime()) {
							returnList.add(cvr);
							break;
						}
					}
				}
			}
		}
		return returnList;
	}

	@Override
	public List<CustomerVisitRecord> searchAll(CustomerVisitRecord cond, String str) {
		List<CustomerVisitRecord> cvrList = queryAll(cond);
		List<CustomerVisitRecord> returnList = new ArrayList<CustomerVisitRecord>();
		if (!cvrList.isEmpty()) {
			returnList = cvrList.stream().filter(a -> a.getCustomer().getPersonalInfo().getName().contains(str))
					.collect(Collectors.toList());
		}
		return returnList;
	}

	@Override
	public Integer queryRemind(CustomerVisitRecord cvr, String type) {
		Integer remindCount = 0;
		if (type.equals("Customer")) {
			List<CustomerVisitRecord> cvrList = query(cvr);
			remindCount = cvrList.size();
		}
		if (type.equals("Member")) {
			TravelContract traCon = new TravelContract();
			traCon.setStatus(Status.Valid);
			traCon.setVisitStatus(VisitStatus.NoVisit);
			traCon.setServicePoint(((CommonUser)AppContext.curUser()).getServicePoint());
			remindCount = travelContractManager.query(traCon).size();
		}
		return remindCount;
	}

}
